import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'

const instance = axios.create({
    baseURL: 'http://interview-api-t.itheima.net/',
    timeout: 5000
})

// 添加请求拦截器
instance.interceptors.request.use(function(config) {
    const token = store.state.user.token
    config.headers.Authorization = `Bearer ${token}`
    return config
}, function(error) {
    return Promise.reject(error)
})

// 添加响应拦截器
instance.interceptors.response.use(function(response) {
    return response
}, function(error) {
    if(error.response.status === 401) {
        Message.error('请重新登录！')
        store.commit('user/logout')
    } else {
        Message.error(error.response.data.message)
    }
    return Promise.reject(error)
})

export default instance
